import { type WritableComputedRef } from "vue";
import { createI18n } from "vue-i18n";

const DEFAULT_LANG = "zh-cn";

export const i18n = createI18n({
  legacy: false,
  locale: DEFAULT_LANG,
  fallbackLocale: DEFAULT_LANG,
});

const loaded = new Set<string>([]);

export async function loadLocaleMessages(locale: string) {
  if (loaded.has(locale)) return;
  const { default: messages } = await import(`./locales/${locale}.json`);
  i18n.global.setLocaleMessage(locale, messages);
  loaded.add(locale);
}

export async function changeLanguage(locale: string) {
  await loadLocaleMessages(locale);
  (i18n.global.locale as WritableComputedRef<string>).value = locale;
  document.querySelector("html")?.setAttribute("lang", locale);
}

loadLocaleMessages(DEFAULT_LANG);
